package com.njtoyo.taxi.admin.service.platform.impl;

import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.njtoyo.taxi.admin.library.Const;
import com.njtoyo.taxi.admin.mapper.master.entity.DriverDeviceAutoPartnerInformation;
import com.njtoyo.taxi.admin.mapper.master.entity.DriverDeviceAutoVersion;
import com.njtoyo.taxi.admin.mapper.master.mapper.DriverDeviceAutoPartnerInformationMapper;
import com.njtoyo.taxi.admin.mapper.master.mapper.DriverDeviceAutoVersionMapper;
import com.njtoyo.taxi.admin.mapper.master.mapper.TaxiLastLocateMapper;
import com.njtoyo.taxi.admin.mapper.secondary.enums.VersionModel;
import com.njtoyo.taxi.admin.mapper.secondary.enums.VersionUserGroup;
import com.njtoyo.taxi.admin.rest.presenter.platfrom.CarAppDevicePresenter;
import com.njtoyo.taxi.admin.rest.presenter.platfrom.CarAppVersionPresenter;
import com.njtoyo.taxi.admin.service.platform.CarAppVersionService;
import com.njtoyo.taxi.admin.utils.StringUtils;
import com.taxi.entity.common.RestResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component
@DS(Const.PRIMARY_DS)
public class CarAppVersionServiceImpl implements CarAppVersionService {
    @Autowired
    private DriverDeviceAutoVersionMapper driverDeviceAutoVersionMapper;
    @Autowired
    private DriverDeviceAutoPartnerInformationMapper driverDeviceAutoPartnerInformationMapper;
    @Autowired
    private TaxiLastLocateMapper taxiLastLocateMapper;

    @Override
    public RestResult list(Integer current, Integer size, String title, VersionModel model, VersionUserGroup userGroup) {
        Page<DriverDeviceAutoVersion> page = new Page<>(current, size);
        Page<CarAppVersionPresenter> appVersionPage = driverDeviceAutoVersionMapper.getPageList(page);
        return RestResult.success(appVersionPage);
    }

    @Override
    public RestResult getDeviceList(Long id) {
//        List<CarAppDevicePresenter> deviceList = driverDeviceAutoVersionMapper.getDeviceList();
        List<CarAppDevicePresenter> deviceList = taxiLastLocateMapper.getDeviceList();
        // 根据plateNumber去重，保留gpsTime最大的记录（null视为最小）
        List<CarAppDevicePresenter> distinctDevices = deviceList.stream()
                .collect(Collectors.toMap(
                        CarAppDevicePresenter::getPlateNumber,
                        device -> device,
                        (existing, replacement) -> {

                                //比较版本号
                                if(StringUtils.isBlank(existing.getVersionInfo()) &&StringUtils.isBlank(replacement.getVersionInfo())){
                                    //版本号为空，返回GPS时间最新的
                                    return existing.getGpsTime().compareTo(replacement.getGpsTime()) > 0
                                            ? existing : replacement;
                                }else if(StringUtils.isBlank(existing.getVersionInfo())){
                                    return replacement;
                                }else if(StringUtils.isBlank(replacement.getVersionInfo())){
                                    return existing;
                                }else{
                                    //留一个版本号大的
                                    return existing.getVersionInfo().compareTo(replacement.getVersionInfo()) > 0
                                            ? existing : replacement;
                                }


                        }
                ))
                .values()
                .stream()
                .collect(Collectors.toList());


        DriverDeviceAutoVersion driverDeviceAutoVersion = driverDeviceAutoVersionMapper.selectById(id);
        for(CarAppDevicePresenter device: distinctDevices){
            JSONObject jsonObject = JSON.parseObject(device.getVersionInfo());
            if(ObjectUtil.isNotNull(jsonObject)){
                device.setVersionInfo(jsonObject.getString("v"));
            }
        }
        Dict result = new Dict();
        result.set("deviceList", distinctDevices);
        if (ObjectUtil.isNotNull(driverDeviceAutoVersion) && StrUtil.isNotBlank(driverDeviceAutoVersion.getDetail())) {
            result.set("detail", JSON.parseArray(driverDeviceAutoVersion.getDetail(), String.class));
        }
        return RestResult.success(result);
    }

    @Override
    public RestResult upgradeDevices(Long id, String deviceIds) {
        String[] strings = deviceIds.split(",");
        DriverDeviceAutoVersion add = new DriverDeviceAutoVersion();
        add.setId(id);
        add.setDetail(JSON.toJSONString(strings));
        driverDeviceAutoVersionMapper.updateById(add);
        return RestResult.success();
    }

    @Override
    public RestResult getDeviceVendor() {
        List<DriverDeviceAutoPartnerInformation> list = driverDeviceAutoPartnerInformationMapper.selectList(null);
        return RestResult.success(list);
    }

    @Override
    public RestResult add(DriverDeviceAutoVersion version) {
        driverDeviceAutoVersionMapper.insert(version);
        return RestResult.success();
    }

    @Override
    public RestResult getInfo(Long id) {
        return RestResult.success(driverDeviceAutoVersionMapper.selectById(id));
    }

    @Override
    public RestResult updateById(Long id, DriverDeviceAutoVersion version) {
        version.setId(id);
        return RestResult.success(driverDeviceAutoVersionMapper.updateById(version));
    }

    @Override
    public RestResult clearDetail(Long id) {
        LambdaUpdateWrapper<DriverDeviceAutoVersion> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.set(DriverDeviceAutoVersion::getDetail, null);
        lambdaUpdateWrapper.eq(DriverDeviceAutoVersion::getId, id);
        driverDeviceAutoVersionMapper.update(null, lambdaUpdateWrapper);
        return RestResult.success();
    }
}
